
# -*- coding: utf-8 -*-

import os
import cv2
import base64
import StringIO
import tornado.web
import numpy as np
from PIL import Image
#from models.User import User
from models.Logs import Logs
from util.FacialRecognition import trainModel
from config import Config
from controllers.BaseController import BaseController
from util.util import getFilesCountByDirectoryPath, initializeModel
from util.FacialRecognition import detect_faces, to_grayscale, crop_faces

class LogsController(BaseController):

	@tornado.web.authenticated
	def post(self):
		if self.request.path == "/logs/save":
			try:
				username = unicode(self.request.arguments["username"][0])
				#user = User.get(username=username)
				distance = int(unicode(self.request.arguments["distance"][0]))
				asknumber = int(unicode(self.request.arguments["asknumber"][0]))
				errornames = unicode(self.request.arguments["errornames"][0])
				blobphoto = self.request.files['blobphoto'][0]['body']
				buffPhoto = StringIO.StringIO(blobphoto) if username != "none" else None
				b64photo = base64.b64encode(buffPhoto.getvalue()) if buffPhoto else None
				log = Logs.create(username=username, distance=distance, asknumber=asknumber,
								  errornames=errornames, b64photo=b64photo)
				log.persist()

				if b64photo is not None:
					if asknumber > 0 or distance >= 60:
						buffPhoto.seek(0)
						photo = np.asarray(Image.open(buffPhoto))
						faces = detect_faces(photo)
						if len(faces) > 0:
							pathUserPhotos = os.path.join(Config.IMAGE_DIR, str(username))
							pathRawUserPhotos = os.path.join(Config.RAW_IMAGE_DIR, str(username))
							photonumber = str(getFilesCountByDirectoryPath(pathUserPhotos) + 1)
							fullPathUserPhotos = os.path.abspath("%s/%s.jpg" % (pathUserPhotos, photonumber))
							fullPathRawUserPhotos = os.path.abspath("%s/%s.jpg" % (pathRawUserPhotos, photonumber))
							cropped = to_grayscale(crop_faces(photo, faces))
							cv2.imwrite(fullPathUserPhotos, cropped)
							cv2.imwrite(fullPathRawUserPhotos, photo)
							Config.STATE_TRAINING_MODEL = True
							initializeModel()
							trainModel()
				return
			except:
				raise tornado.web.HTTPError(400)
		raise tornado.web.HTTPError(404)
